package models


func (tag *Tag) Add() error {

	//return  DB.Create(&tag).Error
	return DB.FirstOrCreate(tag, "name = ?", tag.Name).Error
}

func (pt *PostTag) Insert() error {

	return DB.FirstOrCreate(pt, "post_id=? and tag_id=?", pt.PostId, pt.TagId).Error
	//return DB.Create(&pt).Error
}

func DeletePostTagByPostId(postId uint) error {
	return DB.Delete(&PostTag{}, "post_id = ?", postId).Error
}

func MustListTag() []*Tag {
	tags, _ := ListTag()
	return tags
}

func ListTag() ([]*Tag, error) {
	var tags []*Tag
	rows, err := DB.Raw("select t.*,count(*) total from tags t inner join post_tags pt on t.id = pt.tag_id inner join posts p on pt.post_id = p.id where p.is_published = ? group by pt.tag_id", true).Rows()
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	for rows.Next() {
		var tag Tag
		DB.ScanRows(rows, &tag)
		tags = append(tags, &tag)
	}
	return tags, nil
}